<?php

include "validate.php";

if (isset($_POST["name"]))
	$name = $_POST["name"];
else
	$name = "";
if (isset($_POST["pwd"]))
	$pwd = $_POST["pwd"];
else
	$pwd = "";
if (isset($_POST["pwd2"]))
	$pwd2 = $_POST["pwd2"];
else
	$pwd2 = "";
if (isset($_POST["curr"]))
	$curr = $_POST["curr"];
else
	$curr = "";

$query = "	SELECT COUNT(*) as NUM
			FROM login
			WHERE user_name LIKE '%" . $_SESSION["username"] . "%'
				AND account_pass LIKE '%" . sha1($curr) . "%';";

$result = mysql_query($query);

$row = mysql_fetch_array($result);

if ($row['NUM'] != 0)
{
	if ($row['NUM'] != 1)
	{
		error_log("Login:  Multiple valid users.");
	}
	if (strcmp($pwd, $pwd2) != 0)
	{
		$_POST["message"] = "Passwords Don't Match";
		header("Location:account.php");
	}
	$query = "	SELECT account_id AS id
				FROM login
				WHERE user_name LIKE '%" . $_SESSION["username"] . "%';";
	$result = mysql_query($query);
	if (mysql_num_rows($result) > 1)
	{
		error_log("Update:  Users with same username.");
	}
	if ($row = mysql_fetch_array($result))
	{
		$acc_id = $row['id'];
		if (strlen($pwd) > 0)
		{
			$query = "	UPDATE login 
						SET account_pass = '" . sha1($pwd) . "' 
						WHERE account_id = '" . $acc_id . "';";
			$_SESSION['password'] = $pwd;
			mysql_query($query);
		}
		if (strlen($name) > 0)
		{
			$query = "	UPDATE login 
						SET full_name = '" . $name . "' 
						WHERE account_id = '" . $acc_id . "';";
			mysql_query($query);
		}
		$_SESSION["message"] = "Update Successful!";
		header("Location:account.php");
	}
	else
	{
		header("Location:logout.php");
	}
}
else
{
	$_SESSION["message"] = "Invalid Password";
	header("Location:account.php");
}
?>
